package com.aiton.bamin.bamindaijiadrier.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.app.SysApplication;
import com.aiton.administrator.shane_library.shane.utils.Arith;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.widget.TwoBtnDialog;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.Order;
import com.aiton.bamin.bamindaijiadrier.model.OrderStatue;
import com.aiton.bamin.bamindaijiadrier.model.SendOrder;
import com.aiton.bamin.bamindaijiadrier.server.LocationService;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import cz.msebera.android.httpclient.Header;

public class ComfirmCostActivity extends ZjbBaseActivity implements View.OnClickListener {
    private static final String TAG = "ComfirmCostActivity";
    private Order mOrder;
    private TextView mTextView_name;
    private TextView mTextView_time;
    private TextView mTextView_start;
    private TextView mTextView_end;
    private TextView mTextView_price;
    private BroadcastReceiver recevier = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Constant.BROADCASTCODE.PAY_SUCCESS.equals(action)) {
                String sendOrderValue = intent.getStringExtra(Constant.INTENT_KEY.PAY_SUCCESS);
                Log.e("ComfirmCostActivity", "sendOrderValue: --->>" + sendOrderValue);
                SendOrder mSendOrder = GsonUtils.parseJSON(sendOrderValue, SendOrder.class);
                if (mSendOrder != null) {
                    Log.e("ComfirmCostActivity", "handleMessage: --paySuccess->>" + mSendOrder.getOrderStatus());
                    if (mSendOrder.getAppOrderStatus() == Constant.ORDER_STATUS.NO_EVALUATION) {
                        mTextView_pay_status.setText("乘客支付完成");
//                        mRela_wait_pay.setVisibility(View.GONE);
//                        mRela_success_pay.setVisibility(View.VISIBLE);
                    }
                }
//                Message msg = handler.obtainMessage();
//                msg.obj = paySuccess;
//                handler.sendMessage(msg);
            }
        }
    };
    private LinearLayout mRela_wait_pay;
    //    private RelativeLayout mRela_success_pay;
    private Button mBtn_internet_pay;
    //
//    Handler handler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            PaySuccess paySuccess = (PaySuccess) msg.obj;
//
//            if (paySuccess != null) {
//                Log.e("ComfirmCostActivity", "handleMessage: --paySuccess->>" + paySuccess.getPayStatus() );
//
//                if (paySuccess.getPayStatus().equals("乘客支付完成")) {
//                    mRela_wait_pay.setVisibility(View.GONE);
//                    mRela_success_pay.setVisibility(View.VISIBLE);
//                }
//            }
//        }
//    };
    private Button mBtn_cash_pay;
    private Button mButton_backmain;
    private TextView mTextView_order_mileage;
    private TextView mTextView_order_waiting_time;
    //    private TextView mTextView_order_time_interval;
    private EditText mEdit_comfirm_toll;
    private EditText mEdit_comfirm_other;
    private TextView mTextView_pay_status;
    private double mOtherFees = 0;
    private double mTollFees = 0;
    private LocationService.MyBind mMyBind;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMyBind = (LocationService.MyBind) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private TextView mTextView_order_mileage_money;
    private TextView mTextView_order_waiting_time_money;
    private TextView mTextView_fee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comfirm_cost);
        init();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initViews() {
        String customerName = mOrder.getDatas().getCustomerName();
        if (customerName != null) {
            mTextView_name.setText("乘客：" + customerName);
        } else {
            mTextView_name.setText("乘客：" + mOrder.getDatas().getCustomerPhone());
        }
        mTextView_time.setText("下单时间：" + mOrder.getDatas().getOrderTime());
        mTextView_start.setText(mOrder.getDatas().getStartLocation());
        mTextView_end.setText(mOrder.getDatas().getEndLocation());
//        mTextView_howLong.setText(mOrder.getDatas().getChangeMileage() + "");
        Double mileageCost = mOrder.getDatas().getMileageCost();
        Double fee = mOrder.getDatas().getFee();
        Double waitTimeFee = mOrder.getDatas().getWaitTimeFee();
        Double sumMoney =  mileageCost + fee+waitTimeFee;

        mTextView_price.setText(sumMoney+"");
        mTextView_order_mileage.setText("里程(" + mOrder.getDatas().getMileage() + "公里)");
        mTextView_order_mileage_money.setText(mOrder.getDatas().getMileageCost() + "元");
        mTextView_order_waiting_time.setText("等待费用("+mOrder.getDatas().getWaitTime()+"分钟)");
        mTextView_order_waiting_time_money.setText(mOrder.getDatas().getWaitTimeFee()+"元");
        mTextView_fee.setText(mOrder.getDatas().getFee() + "元");
        if (mOrder.getDatas().getOrderStatus().equals("结算")) {
            mBtn_internet_pay.setVisibility(View.GONE);
            mRela_wait_pay.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void setListeners() {
//        findViewById(R.id.button_change).setOnClickListener(this);
//        findViewById(R.id.img_close).setOnClickListener(this);
        findViewById(R.id.tv_charge_notes).setOnClickListener(this);
        findViewById(R.id.button_backmain).setOnClickListener(this);
        mBtn_internet_pay.setOnClickListener(this);
        mEdit_comfirm_other.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Double mileageCost = mOrder.getDatas().getMileageCost();
                Double fee = mOrder.getDatas().getFee();
                Double waitTimeFee = mOrder.getDatas().getWaitTimeFee();
                Double sumMoney =  mileageCost + fee+waitTimeFee;



                String other = mEdit_comfirm_other.getText().toString().trim();
                if (other.equals("")) {
                    other = "0";
                }
                mOtherFees = Double.parseDouble(other);


                Double add = Arith.add(sumMoney, mOtherFees, mTollFees);
                mTextView_price.setText(add + "");
            }
        });
        mEdit_comfirm_toll.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                Double mileageCost = mOrder.getDatas().getMileageCost();
                Double fee = mOrder.getDatas().getFee();
                Double waitTimeFee = mOrder.getDatas().getWaitTimeFee();
                Double sumMoney =  mileageCost + fee+waitTimeFee;

                String trim = mEdit_comfirm_toll.getText().toString().trim();
                if (trim.equals("")) {
                    trim = "0";
                }
                mTollFees = Double.parseDouble(trim);

                Double add = Arith.add(sumMoney, mTollFees, mOtherFees);
                Log.e("ComfirmCostActivity", "afterTextChanged: --->>" + trim + "add----" + add);
                mTextView_price.setText(add + "");

            }
        });
//        mBtn_cash_pay.setOnClickListener(this);
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mOrder = (Order) intent.getSerializableExtra(Constant.INTENT_KEY.COMFIRM_COST);
    }

    @Override
    protected void findID() {
        mTextView_name = (TextView) findViewById(R.id.textView_name);
        mTextView_time = (TextView) findViewById(R.id.textView_time);
        mTextView_start = (TextView) findViewById(R.id.textView_start);
        mTextView_end = (TextView) findViewById(R.id.textView_end);
        mTextView_price = (TextView) findViewById(R.id.textView_price);
        mTextView_pay_status = (TextView) findViewById(R.id.tv_pay_status);

        mTextView_order_mileage = (TextView) findViewById(R.id.tv_order_mileage);
        mTextView_order_mileage_money = (TextView) findViewById(R.id.tv_order_mileage_money);


        mTextView_order_waiting_time = (TextView) findViewById(R.id.tv_order_waiting_time);
        mTextView_order_waiting_time_money = (TextView) findViewById(R.id.tv_order_waiting_time_money);
        mTextView_fee = (TextView) findViewById(R.id.textView_fee);

        mEdit_comfirm_toll = (EditText) findViewById(R.id.edit_comfirm_toll);
        mEdit_comfirm_other = (EditText) findViewById(R.id.edit_comfirm_other);

        mRela_wait_pay = (LinearLayout) findViewById(R.id.rela_wait_pay);
//        mRela_success_pay = (RelativeLayout) findViewById(R.id.rela_success_pay);
        mBtn_internet_pay = (Button) findViewById(R.id.button_internet_pay);
//        mBtn_cash_pay = (Button) findViewById(R.id.button_cash_pay);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(recevier);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(conn);
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BROADCASTCODE.PAY_SUCCESS);
        registerReceiver(recevier, filter);
        Intent server = new Intent();
        server.setClass(ComfirmCostActivity.this, LocationService.class);
        bindService(server, conn, Context.BIND_AUTO_CREATE);
        startService(server);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_internet_pay://确认

                final TwoBtnDialog twoBtnDialog1 = new TwoBtnDialog(this, "是否确定订单,金额为" + mTextView_price.getText().toString(), "确定", "取消");
                twoBtnDialog1.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        showLoadingDialog();
                        internetPay();
                        mMyBind.startGetOrder();
                        twoBtnDialog1.dismiss();

                    }

                    @Override
                    public void doCancel() {
                        twoBtnDialog1.dismiss();
                    }
                });
                twoBtnDialog1.show();

//                internetPay();
                break;
//            case R.id.img_close:
//                startActivityTo(new Intent(this, MainActivity.class));
//                break;
            case R.id.tv_charge_notes://计费规则
                Intent intent = new Intent();
                intent.setClass(this, ChargesNotesActivity.class);
                intent.putExtra(Constant.INTENT_KEY.TITLE, "收费说明");
                intent.putExtra(Constant.INTENT_KEY.URL, Constant.Url.CHARGES_NOTES);
                startActivityTo(intent);
                break;
            case R.id.button_backmain:

                break;
        }
    }

    /**
     * 网银支付
     */
    private void internetPay() {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        String toll = mEdit_comfirm_toll.getText().toString().trim();
        if (toll.equals("")) {
            toll = "0";
        }
        String other = mEdit_comfirm_other.getText().toString().trim();
        if (other.equals("")) {
            other = "0";
        }
        double tollFees = Double.parseDouble(toll);
        double otherFees = Double.parseDouble(other);
        params.put("orderId", mOrder.getDatas().getId());

        params.put("tollFees", tollFees);
        params.put("otherFees", otherFees);
        String url = Constant.Url.DRIVER_CONFIRM_ORDER;
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("ComfirmCostActivity", "确认:" + s);

                try {
                    OrderStatue orderStatue = GsonUtils.parseJSON(s, OrderStatue.class);
                    Toast.makeText(ComfirmCostActivity.this, "" + orderStatue.getMes(), Toast.LENGTH_SHORT).show();

                    startActivityTo(new Intent(ComfirmCostActivity.this, MainActivity.class));
                    finishTo();
                    cancelLoadingDialog();

                } catch (Exception e) {
                    Toast.makeText(ComfirmCostActivity.this, "网络解析出错", Toast.LENGTH_SHORT).show();
                    Log.e("ComfirmCostActivity", "onSuccess: --->>网络解析出错");

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(ComfirmCostActivity.this, "网络请求出错", Toast.LENGTH_SHORT).show();
                Log.e("ComfirmCostActivity", "onFailure: --->>网络请求出错");

            }
        });

    }

    private void changeMileageDialog() {
        final Dialog alertDialogChangeMileage = new Dialog(this, R.style.dialog);
        View change_mileage = getLayoutInflater().inflate(R.layout.change_mileage, null);
        alertDialogChangeMileage.setContentView(change_mileage);
        final EditText editText_mileage = (EditText) change_mileage.findViewById(R.id.editText_mileage);
        change_mileage.findViewById(R.id.button_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialogChangeMileage.dismiss();
            }
        });
        change_mileage.findViewById(R.id.button_commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog();
                AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
                RequestParams params = new RequestParams();
                String url = Constant.Url.DRIVER_CHANGE_MILEAGE;
                params.put("orderId", mOrder.getDatas().getId());
                params.put("mileage", editText_mileage.getText().toString().trim());
                asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        String s = new String(responseBody);
                        Log.e("onSuccess ", "更改公里数的返回值" + s);
                        try {
                            mOrder = GsonUtils.parseJSON(s, Order.class);
//                            mTextView_howLong.setText(editText_mileage.getText().toString().trim());
                            mTextView_price.setText(mOrder.getDatas().getMileageCost() + "");
                            cancelLoadingDialog();
                            alertDialogChangeMileage.dismiss();
                        } catch (Exception e) {

                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                    }
                });
            }
        });
        Window dialogWindow = alertDialogChangeMileage.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = ComfirmCostActivity.this.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        lp.width = (int) (d.widthPixels * 0.8); // 高度设置为屏幕的0.6
        dialogWindow.setAttributes(lp);
        alertDialogChangeMileage.show();
    }

    @Override
    public void onBackPressed() {
        SysApplication.getInstance().exit();
        startActivityTo(new Intent(this, MainActivity.class));
    }
}
